﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using MMy.Core.FrameWork.Attributes;
using My.Core.Common.Helper;
using My.Core.FrameWork.Auth.Policys;
using My.Core.Model;
using My.Core.Model.Models;
using My.Core.Model.ViewModel;
//using My.Core.Model.ViewModel.FrameworMenu;
//using EntityFramework.Extensions;
namespace MyCore.Api
{
    /// <summary>
    /// 系统菜单
    /// </summary>
    [ActionDescriptionAttribute("系统菜单管理")]
    [Route("api/FrameworkMenuApi")]
    [ApiController]
  
    public class FrameworkMenuApiController : ControllerBase
    {
        private IActionDescriptorCollectionProvider _actionProvider;
        private ApplicationPartManager _applicationPartManager;
        private Appsettings _uiSetting;
        /// <summary>
        /// 数据库
        /// </summary>
        public MyDbContext _myDbContext;
        /// <summary>
        /// 默认注入
        /// </summary>
        /// <param name="actionDescriptorCollectionProvider"></param>
        /// <param name="applicationPartManager"></param>
        public FrameworkMenuApiController(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider, ApplicationPartManager applicationPartManager, IOptions<Appsettings> options, MyDbContext myDbContext)
        {
            _applicationPartManager = applicationPartManager;
            _actionProvider = actionDescriptorCollectionProvider;
            _uiSetting = options.Value;
            _myDbContext = myDbContext;
        }

        /// <summary>
        /// 获取所有模块V2
        /// </summary>
        /// <returns></returns>
        [ActionDescriptionAttribute("获取所有模块V2")]
        [AllowAnonymous]
        [HttpGet("GetAllModules")]
        public IActionResult GetAllModules()
        {
            //var service = HttpContext.RequestServices.GetService(typeof(Appsettings)) as Appsettings;
            var assembly = typeof(Startup).Assembly.GetTypes().AsEnumerable()
           .Where(type => typeof(ControllerBase).IsAssignableFrom(type))
           .Where(x => x.IsDefined(typeof(ActionDescriptionAttribute), false)).ToList(); //获取 继承ControllerBase的控制器 具有(ActionDescriptionAttribute)特性

            List<dynamic> dynamics = new List<dynamic>();
            assembly.ForEach(r =>
            {

                var actionDescription = r.GetCustomAttribute<ActionDescriptionAttribute>(); //获取控制器上特性描述
                if (actionDescription != null)
                {
                    if (r.Name.EndsWith("Controller"))
                    {
                        var controllerName = r.Name.Substring(0,
                            r.Name.Length - "Controller".Length);
                        string LinkUrl = "/";
                        if (r.Name.EndsWith("ApiController"))
                        {
                            LinkUrl += "Api" + "/" + controllerName;

                        }
                        else
                        {
                            LinkUrl += controllerName;
                        }
                        dynamics.Add(new { LinkUrl = LinkUrl, ControllerName = controllerName, FullName = r.FullName, ModuleName = actionDescription.Description });
                    }
                }
            });
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(dynamics), "application/json");
        }



        /// <summary>
        /// 获取模块对应的动作
        /// </summary>
        /// <param name="ModuleName"></param>
        /// <returns></returns>
        //  [Authorize("MyPermission")]
        [ActionDescriptionAttribute("获取模块对应的动作")]
        [AllowAnonymous]
        [HttpGet("GetModuleAction/{ModuleName}")]
        public List<FrameworkActionView> GetModuleAction(string ModuleName)
        {

            return GetAction(ModuleName);
        }

        private List<FrameworkActionView> GetAction(string ModuleName)
        {
            List<FrameworkActionView> frameworkMenus = new List<FrameworkActionView>();

            var actionDescs = _actionProvider.ActionDescriptors.Items.OfType<ControllerActionDescriptor>().Where(x => x.ControllerName == ModuleName);
            foreach (var u in actionDescs)
            {
                var routeTemplate = u.AttributeRouteInfo.Template;//控制器要加[Route("[controller]/[action]")]不然就报错
                var pageName = u.MethodInfo.GetCustomAttributes<ActionDescriptionAttribute>().FirstOrDefault()?.Description;
                string controllerName = u.ControllerTypeInfo.GetCustomAttribute<ActionDescriptionAttribute>()?.Description; //控制器上特性描述
                string controller = u.ControllerName; //控制器名称
                string actionName = u.MethodInfo.GetCustomAttributes<ActionDescriptionAttribute>().FirstOrDefault()?.Description;//动作上特性描述
                string action = u.ActionName;//动作名称
                string className = u.ControllerTypeInfo.FullName;
                var _controllRountTemplate = actionDescs.FirstOrDefault().ControllerTypeInfo.GetCustomAttribute<RouteAttribute>().Template;//控制器要加[Route("[controller]/[action]")]不然就报错
                frameworkMenus.Add(new FrameworkActionView
                {
                    PageName = pageName,
                    ActionName = actionName,
                    Action = action,
                    ControllerName = controllerName,
                    Controller = controller,
                    LinkUrl = routeTemplate,
                    ClassName = className,
                    ModuleRountTemplate = _controllRountTemplate

                });
            }
            return frameworkMenus;
        }


        /// <summary>
        /// 菜单管理
        /// </summary>
        /// <returns></returns>
        [ActionDescriptionAttribute("菜单管理")]
        [HttpGet("GetMens")]
        [Authorize("MyPermission")]
        public List<FrameworkMensView> GetMens()
        {

            var userid = HttpContext.User.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Jti).FirstOrDefault()?.Value;//登录后用户id

            List<int?> roleIds = new List<int?>();    //用户角色
            _myDbContext.FrameworkUserRoles.AsNoTracking().Where(x => x.UserId == userid.ObjToInt() && x.IsDeleted == false).Select(x => new { x.RoleId })
            .Distinct().ToList().ForEach(x => { roleIds.Add(x.RoleId.ObjToInt()); });

            List<int?> menids = new List<int?>();

            _myDbContext.FrameworkRoleMenuPermissions.Include(x => x.MenuItem).Where(x => x.IsDeleted == false && roleIds.Contains(x.RoleId)).Select(x => new
            {
                x.MenuItem.Id
            }).Distinct().ToList().ForEach(x => { menids.Add(x.Id); });
            var menuInfos = _myDbContext.FrameworkMenus.Where(x => menids.Contains(x.Id)).OrderBy(x => x.OrderSort).ThenBy(x => x.Id).Select(u => new FrameworkMensView
            {
                PageName = u.PageName,
                ParentId = u.ParentId,
                IsDir = u.IsDir,
                IsMenu = u.IsMenu,
                ModuleName = u.ControllerName,
                OrderSort = u.OrderSort,
                Icon = u.Icon,
                Id = u.Id,
                Level = 1,//第一级
                Childrens = new List<FrameworkMensView>()
            }).OrderBy(x => x.OrderSort).ThenBy(x => x.Id).ToList();
            return GetMenItems(menuInfos, new List<FrameworkMensView>(), 0, 1);
        }


        /// <summary>
        /// 新建菜单
        /// </summary>
        /// <param name="Men">菜单</param>
        /// <param name="PageName">页面名称</param>
        /// <param name="IsMen">是否菜单 true是 false否</param>
        /// <param name="IsDir">是否目录  true是 false否</param>
        /// <param name="ParentId">父级ID 0为根目录</param>
        /// <returns></returns>
        [ActionDescriptionAttribute("新建菜单")]
        [HttpPost("CreateMenus/{PageName}/{IsMen}/{IsDir}/{ParentId}")]
        //[Authorize("MyPermission")]
        public ResponseMessageModel<CreateFrameworkMenView> CreateMenus(CreateFrameworkMenView Men, string PageName, bool IsMen, bool IsDir, int ParentId = 0)
        {
            //1.若果是菜单和目录 显示在 admin后台左侧树中  
            //2如果是目录不是菜单时 不显示在树节点中  可以不选择模块
            //3. 只要不是目录 需要选择模块

            var responseMessageModel = new ResponseMessageModel<CreateFrameworkMenView>() { Success = true };
            List<int> rolesList = new List<int>();
            if (Men.Roles.Count == 0)
            {
                responseMessageModel.Msg = "请选择角色";
                responseMessageModel.Status = -1;
                responseMessageModel.Success = false;
                return responseMessageModel;
            }

            List<FrameworkMenu> frameworkMenusAdds = new List<FrameworkMenu>();
            List<FrameworkRoleMenuPermission> frameworkCreateRoleMenu = new List<FrameworkRoleMenuPermission>();
            if (IsDir == true)
            {
                var dir = new FrameworkMenu
                {

                    PageName = PageName,
                    ActionName = "目录",
                    Action = "目录",
                    ControllerName = "目录",
                    Controller = "目录",
                    IsDeleted = false,
                    IsDir = IsDir,
                    IsMenu = IsMen,
                    LinkUrl = "/",
                    ParentId = ParentId //父目录
                };
                _myDbContext.FrameworkMenus.Add(dir);
                _myDbContext.SaveChanges();

                foreach (var role in Men.Roles)
                {
                    frameworkCreateRoleMenu.Add(new FrameworkRoleMenuPermission
                    {
                        RoleId = role.Id,
                        MenuItemId = dir.Id,
                        IsDeleted = false
                    });
                }
                if (frameworkCreateRoleMenu.Count > 0)
                {
                    _myDbContext.FrameworkRoleMenuPermissions.AddRange(frameworkCreateRoleMenu);
                    _myDbContext.SaveChanges();
                }
            }
            else
            {
                List<string> AddroutsUrls = new List<string>();
                Men.Actions.Where(x => x.SumityType == SumityTypeEnum.Add).ToList().ForEach(x => { AddroutsUrls.Add(x.LinkUrl); });
                var actionDescs = _actionProvider.ActionDescriptors.Items.OfType<ControllerActionDescriptor>().Where(x => AddroutsUrls.Contains(x.AttributeRouteInfo.Template));
                var _Controller = actionDescs.FirstOrDefault()?.ControllerName;//路由中的控制器名称
                var _ControllerName = actionDescs.FirstOrDefault()?.ControllerTypeInfo.GetCustomAttribute<ActionDescriptionAttribute>()?.Description;
                var _ClassName = actionDescs.FirstOrDefault()?.ControllerTypeInfo.FullName;
                var _controllRountTemplate = actionDescs.FirstOrDefault().ControllerTypeInfo.GetCustomAttribute<RouteAttribute>().Template;//控制器要加[Route("[controller]/[action]")]不然就报错
                var Mens = new FrameworkMenu
                {

                    PageName = PageName,
                    ActionName = "",
                    Action = "",
                    ControllerName = _ControllerName,
                    Controller = _Controller,
                    IsDeleted = false,
                    LinkUrl = _controllRountTemplate,
                    IsDir = IsDir,
                    IsMenu = IsMen,
                    ClassName = _ClassName,
                    ParentId = ParentId //父目录
                };
                _myDbContext.FrameworkMenus.Add(Mens);
                _myDbContext.SaveChanges();

                foreach (var role in Men.Roles)
                {
                    frameworkCreateRoleMenu.Add(new FrameworkRoleMenuPermission
                    {
                        RoleId = role.Id,
                        MenuItemId = Mens.Id,
                        IsDeleted = false
                    });
                }
                foreach (var u in actionDescs)
                {
                    string controllerName = u.ControllerTypeInfo.GetCustomAttribute<ActionDescriptionAttribute>()?.Description; //控制器上特性描述
                    string controller = u.ControllerName; //控制器名称
                    string actionName = u.MethodInfo.GetCustomAttributes<ActionDescriptionAttribute>().FirstOrDefault()?.Description;//动作上特性描述
                    string action = u.ActionName;//动作名称
                    var routeTemplate = u.AttributeRouteInfo.Template;//控制器要加[Route("[controller]/[action]")]不然就报错
                    string className = u.ControllerTypeInfo.FullName;
                    frameworkMenusAdds.Add(new FrameworkMenu
                    {

                        PageName = actionName,
                        ActionName = actionName,
                        Action = action,
                        LinkUrl = routeTemplate,
                        ControllerName = controllerName,
                        Controller = controller,
                        IsDeleted = false,
                        IsDir = IsDir,
                        IsMenu = IsMen,
                        ClassName = className,
                        ParentId = Mens.Id //菜单Id

                    });
                }
            }
            if (frameworkMenusAdds.Count > 0)
            {
                _myDbContext.FrameworkMenus.AddRange(frameworkMenusAdds);
                int res = _myDbContext.SaveChanges();
                if (res > 0)
                {
                    foreach (var rolemen in frameworkMenusAdds)
                    {
                        foreach (var role in Men.Roles)
                        {
                            frameworkCreateRoleMenu.Add(new FrameworkRoleMenuPermission
                            {
                                RoleId = role.Id,
                                MenuItemId = rolemen.Id,
                                CreateTime = System.DateTime.Now,
                                IsDeleted = false
                            });
                        }
                    }
                }
            }
            if (frameworkCreateRoleMenu.Count > 0)
            {
                _myDbContext.FrameworkRoleMenuPermissions.AddRange(frameworkCreateRoleMenu);
                _myDbContext.SaveChanges();
            }

            responseMessageModel.Msg = "创建成功";
            return responseMessageModel;
        }

        /// <summary>
        /// 编辑菜单项 
        /// </summary>
        /// <param name="Id">菜单Id</param>
        /// <returns></returns>
        [ActionDescriptionAttribute("编辑菜单项")]
        [HttpGet("GetActionsByModelId/{Id}")]
        [Authorize("MyPermission")]
        public ResponseMessageModel<EditFrameworkMenView> GetActionsByModelId(int Id)
        {
            var men = _myDbContext.FrameworkMenus.AsNoTracking().Where(x => x.Id == Id).FirstOrDefault();

            return GetActionsByModelId_Service(Id, men);
        }
        private ResponseMessageModel<EditFrameworkMenView> GetActionsByModelId_Service(int Id, FrameworkMenu men)
        {

            EditFrameworkMenView menview = new EditFrameworkMenView();
            menview.Roles = new List<FrameworkRoleView>();
            menview.Actions = new List<EidtFrameworkMenActionView>();
            var responseMessageModel = new ResponseMessageModel<EditFrameworkMenView>() { Success = true };
            if (men == null)
            {
                responseMessageModel.Success = false;
                responseMessageModel.Msg = "菜单不存在";
                return responseMessageModel;
            }
            //登录后用户id
            var userid = HttpContext.User.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Jti).FirstOrDefault()?.Value;

            //用户对应的多个角色
            List<int?> roleIds = new List<int?>();
            var roles = _myDbContext.FrameworkUserRoles.Include(x => x.Role).AsNoTracking().Where(x => x.UserId == userid.ObjToInt()).Select(x => new { x.RoleId, x.Role.Name }).ToList();
            roles.Select(x => new
            {
                x.RoleId
            }).Distinct().ToList().ForEach(x =>
            {
                roleIds.Add(x.RoleId.ObjToInt());
            });

            menview.Id = men.Id;//Id
            menview.Icon = men.Icon;
            menview.PageName = men.PageName;
            menview.IsDir = men.IsDir;
            menview.IsMenu = men.IsMenu;
            menview.ControllerName = men.ControllerName; //如果为目录这无用
            menview.Controller = men.Controller;//如果为目录这无用
            menview.ParentId = men.ParentId;//父Id

            //前端要展示的角色
            var frameworkRoleMenuPermissions_Roles = _myDbContext.FrameworkRoleMenuPermissions.Where(x => x.MenuItemId == x.MenuItemId && roleIds.Contains(x.RoleId)).Select(x => new
            {
                x.MenuItemId,
                x.RoleId,

            }).ToList();
            frameworkRoleMenuPermissions_Roles.Select(x => new { x.RoleId }).Distinct().ToList().ForEach(x =>
            {
                menview.Roles.Add(new FrameworkRoleView() { Id = x.RoleId.ObjToInt(), Name = roles.Where(c => c.RoleId == x.RoleId).FirstOrDefault()?.Name });
            });

            //首先判断是否是目录
            if (men.IsDir == true)
            {

                responseMessageModel.ResponseData = menview;
                return responseMessageModel;
            }
            else
            {
                List<int?> menids = new List<int?>();
                //角色可以访问的菜单
                frameworkRoleMenuPermissions_Roles.Distinct().ToList().ForEach(x => { menids.Add(x.MenuItemId); });


                //先找出之前保存的菜单的 属于该模块的action   有权限的        //bug saveActions中再控制器中没找到的情况正常不会有。???
                var saveActions = _myDbContext.FrameworkMenus.AsNoTracking().Where(x => x.ParentId == men.Id && x.IsDir == false && menids.Contains(x.Id)).ToList();
                //找出控制器上对应的 action
                var assemblyaAtions = GetAction(men.Controller);
                foreach (var at in assemblyaAtions)
                {
                    var e = saveActions.Where(x => x.LinkUrl == at.LinkUrl).FirstOrDefault();
                    if (e != null)
                    {
                        menview.Actions.Add(new EidtFrameworkMenActionView { Id = e.Id, ParentId = men.ParentId, ActionName = at.ActionName, LinkUrl = at.LinkUrl, Selected = true, SumityType = SumityTypeEnum.Show });
                    }
                    else
                    {
                        menview.Actions.Add(new EidtFrameworkMenActionView { Id = 0, ParentId = men.ParentId, ActionName = at.ActionName, LinkUrl = at.LinkUrl, Selected = false, SumityType = SumityTypeEnum.Add });
                    }
                }

            }

            responseMessageModel.ResponseData = menview;
            return responseMessageModel;
        }




        /// <summary>
        /// 编辑菜单项 切换模块 
        /// </summary>
        /// <param name="Id">菜单Id</param>
        /// <param name="ModuleName">模块名(切换模块改变)</param>
        /// <returns></returns>
        [ActionDescriptionAttribute("编辑切换模块")]
        [HttpGet("GetDownListModule/{Id}/{ModuleName}")]
        [Authorize("MyPermission")]
        public ResponseMessageModel<EditFrameworkMenView> GetDownListModule(int Id, string ModuleName)
        {
            EditFrameworkMenView menview = new EditFrameworkMenView();
            menview.Roles = new List<FrameworkRoleView>();
            menview.Actions = new List<EidtFrameworkMenActionView>();
            var responseMessageModel = new ResponseMessageModel<EditFrameworkMenView>() { Success = true };
            var men = _myDbContext.FrameworkMenus.AsNoTracking().Where(x => x.Id == Id).FirstOrDefault();
            if (men == null)
            {
                responseMessageModel.Success = false;
                responseMessageModel.Msg = "菜单不存在";
                return responseMessageModel;
            }
            if (men.Controller == ModuleName)
                return GetActionsByModelId_Service(men.Id, men);

            var assemblyaAtions = GetAction(ModuleName);
            foreach (var at in assemblyaAtions)
            {
                menview.Actions.Add(new EidtFrameworkMenActionView { Id = 0, ParentId = men.ParentId, ActionName = at.ActionName, LinkUrl = at.LinkUrl, Selected = true, SumityType = SumityTypeEnum.Add });
            }

            responseMessageModel.ResponseData = menview;
            return responseMessageModel;
        }



        /// <summary>
        /// 编辑提交菜单
        /// </summary>
        /// <param name="Men">当前菜单</param>
        /// <param name="MenId">菜单Id</param>
        /// <param name="ModuleName">模块名(切换模块改变)</param>
        /// <returns></returns>
        /// 
        
        [ActionDescriptionAttribute("编辑提交菜单")]
        [HttpPost("EditSubmitMen/{MenId}/{ModuleName}")]
        [Authorize("MyPermission")]
        public ResponseMessageModel<EditFrameworkMenView> EditSubmitMen(EditFrameworkMenView Men, int MenId, string ModuleName)
        {
            EditFrameworkMenView menview = new EditFrameworkMenView();
            var responseMessageModel = new ResponseMessageModel<EditFrameworkMenView>() { Success = true };
            if (Men.Id == 0) Men.Id = MenId;
            if (string.IsNullOrEmpty(Men.Controller)) Men.Controller = ModuleName;
            var menEntity = _myDbContext.FrameworkMenus.Where(x => x.Id == Men.Id).FirstOrDefault();
            if (menEntity == null)
            {
                responseMessageModel.Success = false;
                responseMessageModel.Msg = "菜单不存在";
                return responseMessageModel;
            }
            //登录后用户id
            var userid = HttpContext.User.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Jti).FirstOrDefault()?.Value;
            //用户对应的多个角色
            List<int?> roleIds = new List<int?>();
            Men.Roles.ForEach(x =>
            {
                roleIds.Add(x.Id.ObjToInt());
            });
            //是否是目录
            if (Men.IsDir == true)
            {
                //是目录 action不用管了 会有问题 ???
                //更新目录

                menEntity.PageName = Men.PageName;
                menEntity.IsMenu = Men.IsMenu;
                menEntity.Controller = "";
                menEntity.ControllerName = "目录";
                menEntity.Action = "";
                menEntity.ActionName = "目录";
                menEntity.LinkUrl = "/";
                menEntity.ClassName = "";

                menEntity.ParentId = Men.ParentId;
                _myDbContext.SaveChanges();

                var RemoveIds = _myDbContext.FrameworkRoleMenuPermissions.Where(x => x.MenuItemId == menEntity.Id && !roleIds.Contains(x.RoleId)).ToList();
                foreach (var removeEntity in RemoveIds)
                {
                    _myDbContext.FrameworkRoleMenuPermissions.Remove(removeEntity);
                }
                if (RemoveIds.Count > 0) _myDbContext.SaveChanges();



                foreach (var r in Men.Roles)
                {

                    var framedir = _myDbContext.FrameworkRoleMenuPermissions.Where(x => x.MenuItemId == menEntity.Id && x.RoleId == r.Id).FirstOrDefault();
                    if (framedir == null)
                    {
                        _myDbContext.FrameworkRoleMenuPermissions.Add(new FrameworkRoleMenuPermission() { MenuItemId = menEntity.Id, RoleId = r.Id, CreateTime = System.DateTime.Now, IsDeleted = false });
                        _myDbContext.SaveChanges();
                    }
                }
            }
            else
            {
                //如果控制器下一个都没有
                var assemblyaAtions = GetAction(ModuleName);
                menEntity.LinkUrl = assemblyaAtions.FirstOrDefault()?.ModuleRountTemplate;
                menEntity.PageName = Men.PageName;
                menEntity.IsDeleted = false;
                menEntity.IsDir = false;
                menEntity.IsMenu = Men.IsMenu;
                menEntity.Controller = assemblyaAtions.FirstOrDefault()?.Controller;
                menEntity.ControllerName = assemblyaAtions.FirstOrDefault()?.ControllerName;
                menEntity.ClassName = assemblyaAtions.FirstOrDefault()?.ClassName;
                menEntity.ParentId = Men.ParentId;
                menEntity.LinkUrl = assemblyaAtions.FirstOrDefault()?.ModuleRountTemplate;
                menEntity.ModifyTime = System.DateTime.Now;
                _myDbContext.SaveChanges();
                //var addRolenMen = new List<FrameworkRoleMenuPermission>();
                //var delRolenMen = new List<FrameworkRoleMenuPermission>();
                //这块后期优化  批量改 或者关联删
                var BeforeSavaframeMenActions = _myDbContext.FrameworkMenus.AsNoTracking().Where(x => x.ParentId == menEntity.Id).ToList();  //之前保存过的actions

                foreach (var befac in BeforeSavaframeMenActions)
                {
                    if (!Men.Actions.Where(x => x.Selected == true).Any(x => x.LinkUrl == befac.LinkUrl))
                    {
                        var RemoveIds = _myDbContext.FrameworkRoleMenuPermissions.Where(x => x.MenuItemId == befac.Id).ToList();
                        foreach (var removeEntity in RemoveIds)
                        {
                            _myDbContext.FrameworkRoleMenuPermissions.Remove(removeEntity);
                        }
                        if (RemoveIds.Count > 0) _myDbContext.SaveChanges();
                        _myDbContext.FrameworkMenus.Remove(befac);
                        _myDbContext.SaveChanges();
                    }
                }

                foreach (var ac in Men.Actions.Where(x => x.Selected == true))
                {
                    var entity = assemblyaAtions.Where(x => x.LinkUrl == ac.LinkUrl).FirstOrDefault();
                    var b = BeforeSavaframeMenActions.Where(x => x.LinkUrl == ac.LinkUrl).FirstOrDefault();
                    if (b == null)
                    {
                        var addentity = new FrameworkMenu()
                        {
                            PageName = entity?.ActionName,
                            IsDeleted = false,
                            IsDir = false,
                            IsMenu = Men.IsMenu,
                            Controller = entity?.Controller,
                            ControllerName = entity?.ControllerName,
                            ClassName = entity?.ClassName,
                            ParentId = Men.Id,
                            LinkUrl = entity?.LinkUrl,
                            Action = entity?.Action,
                            ActionName = entity?.ActionName,

                            CreateTime = System.DateTime.Now
                        };
                        _myDbContext.FrameworkMenus.Add(addentity);

                        _myDbContext.SaveChanges();
                        ac.MenId = addentity.Id;
                    }
                    else
                    {
                        ac.MenId = b.Id;
                    }
                }
                foreach (var r in Men.Roles)
                {
                    foreach (var ac in Men.Actions.Where(x => x.Selected == true))
                    {


                        var frameaction = _myDbContext.FrameworkRoleMenuPermissions.AsNoTracking().Where(x => x.MenuItemId == ac.MenId && x.RoleId == r.Id).FirstOrDefault();
                        if (frameaction == null)
                        {
                            _myDbContext.FrameworkRoleMenuPermissions.Add(new FrameworkRoleMenuPermission() { MenuItemId = ac.MenId, RoleId = r.Id, CreateTime = System.DateTime.Now, IsDeleted = false });
                            _myDbContext.SaveChanges();
                        }
                    }
                }
            }


            responseMessageModel.Msg = "保存成功";
            responseMessageModel.ResponseData = menview;
            return responseMessageModel;
        }


        /// <summary>
        /// 递归子第一种
        /// </summary>
        /// <param name="menusinfo"></param>
        /// <param name="childrens"></param>
        /// <param name="pid"></param>
        /// <param name="level"></param>
        /// <returns></returns>

        private List<FrameworkMensView> GetMenItems(List<FrameworkMensView> menusinfo, List<FrameworkMensView> childrens, int pid, int level)
        {
            var frameworkMenuList = menusinfo.Where(x => x.ParentId == pid).OrderBy(x => x.OrderSort).ThenBy(x => x.Id).ToList();
            foreach (var men in frameworkMenuList)
            {
                men.Level = level;//层级
                childrens.Add(men);
                GetMenItems(menusinfo, men.Childrens, men.Id, level + 1);

            }
            return frameworkMenuList;
        }


        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="MenId">菜单Id</param>
        /// <returns></returns>
        [ActionDescriptionAttribute("删除菜单")]
        [HttpPost("DelSubmitMen/{MenId}")]
        [Authorize("MyPermission")]
        public ResponseMessageModel<int> DelSubmitMen(int MenId)
        {
            var mode = new ResponseMessageModel<int>();
            return mode;
        }

    }

}








//private IEnumerable<dynamic> List()
//{
//    var actionDescs = _actionProvider.ActionDescriptors.Items.Cast<ControllerActionDescriptor>().Select(x => new
//    {
//        ControllerName = x.ControllerName,
//        ActionName = x.ActionName,
//        DisplayName = x.DisplayName,
//        RouteTemplate = x.AttributeRouteInfo.Template,
//        Attributes = x.MethodInfo.CustomAttributes.Select(z => new
//        {
//            TypeName = z.AttributeType.FullName,
//            ConstructorArgs = z.ConstructorArguments.Select(v => new
//            {
//                ArgumentValue = v.Value
//            }),
//            NamedArguments = z.NamedArguments.Select(v => new
//            {
//                v.MemberName,
//                TypedValue = v.TypedValue.Value,
//            }),
//        }),
//        ActionId = x.Id,
//        x.RouteValues,
//        Parameters = x.Parameters.Select(z => new
//        {
//            z.Name,
//            TypeName = z.ParameterType.Name,
//        })
//    });

//    return actionDescs;
//}

/*
/// <summary>
/// 获取模块V1
/// </summary>
/// <returns></returns>
[ActionDescriptionAttribute("获取模块V1")]
[HttpGet("GetModules")]
public IActionResult GetModules()
{
    var controllerFeature = new ControllerFeature();
    _applicationPartManager.PopulateFeature(controllerFeature);
    foreach (var x in controllerFeature.Controllers)
    {
        var ModuleName = x.Module.Name;
        var Actions = x.DeclaredMethods.Where(m => m.IsPublic && !m.IsDefined(typeof(NonActionAttribute)));
        foreach (var ac in Actions)
        {
            var Name = ac.Name;
            var Parameters = ac.GetParameters();
            foreach (var z in Parameters)
            {
                if (Name == "GetAllMenuItemTest")
                {
                    int bb = 1;
                }
            }
        }


    }
    var actionDescs = _actionProvider.ActionDescriptors.Items.OfType<ControllerActionDescriptor>().Select(x => new
    {
        RouteTemplate = x.AttributeRouteInfo.Template,//控制器要加[Route("[controller]/[action]")]不然就报错
        ControllerName = x.ControllerName,
        ActionName = x.ActionName,
        RouteValues = x.RouteValues
    }).ToList();
    foreach (var u in actionDescs)
    {


    }
    var data = controllerFeature.Controllers.Select(x => new
    {

        Namespace = x.Namespace,
        Controller = x.FullName,
        ModuleName = x.Module.Name,
        Actions = x.DeclaredMethods.Where(m => m.IsPublic && !m.IsDefined(typeof(NonActionAttribute))).Select(y => new
        {
            Name = y.Name,
            ParameterCount = y.GetParameters().Length,
            Parameters = y.GetParameters()
             .Select(z => new
             {
                 z.Name,
                 z.ParameterType.FullName,
                 z.Position,
                 Attrs = z.CustomAttributes.Select(m => new
                 {
                     FullName = m.AttributeType.FullName,
                 })
             })
        }),
    }); ;
    return new JsonResult(data);
}
*/
